//
//  ZDBInformationViewController.m
//  ZDB
//
//  Created by 微笑吧阳光 on 2020/3/26.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBInformationViewController.h"
#import "PerfectInformationView.h"
#import "BDImagePicker.h"

@interface ZDBInformationViewController ()<TZImagePickerControllerDelegate>
@property(nonatomic,strong)PerfectInformationView * infoView;
@property(strong,nonatomic)UIImage * selectImage;
@property(strong,nonatomic)NSString * kUploadIconImageToken;
@property(strong,nonatomic)NSString * imageKey;

@end

@implementation ZDBInformationViewController
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
   self.infoView.frame = CGRectMake(0, 0, kScreenWidth, 375);
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self creat_UI];
    [self getAvatarQiniuToken];
    
}

-(void)creat_UI{
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton * reBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    reBtn.frame = CGRectMake(0, -10, 50, 40);
    //     [reBtn setImage:[UIImage imageNamed:@"goBack"] forState:UIControlStateNormal];
    [reBtn setTitle:@"跳过" forState:0];
    [reBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [reBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:0];
    [reBtn addTarget:self action:@selector(reBtnClik) forControlEvents:UIControlEventTouchUpInside];
    reBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:reBtn];
    
    
    self.infoView = [[NSBundle mainBundle] loadNibNamed:@"PerfectInformationView" owner:self options:nil].lastObject;
    self.infoView.frame = CGRectMake(0, 0, kScreenWidth, 375);
    [self.view addSubview:self.infoView];
    
    WEAKSELF
    [self.infoView.sureBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf)
        [strongSelf updateNickNameAndHeadImage];
    }];
    
    [self.infoView.editHeaderBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf editHeaderBtnClick];
    }];
    
    [self.infoView.nameTF addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];

}
-(void)changedTextField:(UITextField *)textField
{
    
    [RestrictionInput restrictionInputTextField:textField maxNumber:12 showView:self.view showErrorMessage:@"0~12字符~"];
    
    
}
- (BOOL)JudgeTheillegalCharacter:(NSString *)content{
 //提示 标签不能输入特殊字符
 NSString *str =  @"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
//@"^[A-Za-z0-9\\u4e00-\u9fa5]+$”;
 NSPredicate * emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
 if (![emailTest evaluateWithObject:content]) {
 return YES;
 }
 return NO;
}

-(void)editHeaderBtnClick{
    
    WEAKSELF
//    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
//        STRONGSELFFor(weakSelf)
//
//        if (image) {
//            strongSelf.selectImage = image;
//            strongSelf.infoView.headerImage.image = strongSelf.selectImage;
//            [strongSelf upLoadImageToQINiu:image andBlock:^(NSString *imageKey) {
//                NSLog(@"imageKey----%@",imageKey);
//                strongSelf.imageKey = imageKey;
//            }];
//        }
//    }];
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
      imagePickerVc.allowTakeVideo = NO;
      imagePickerVc.allowPickingGif = NO;
      imagePickerVc.needCircleCrop = YES;
      imagePickerVc.allowCrop = YES;
      imagePickerVc.barItemTextColor = [UIColor colorWithHexString:@"#333333"];
      imagePickerVc.naviTitleColor = [UIColor colorWithHexString:@"#333333"];
      [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
          [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
      }];
      [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
          STRONGSELFFor(weakSelf);
          if (photos.count >0) {
              strongSelf.selectImage =photos.firstObject;
              strongSelf.infoView.headerImage.image = strongSelf.selectImage;
                          [strongSelf upLoadImageToQINiu:self.selectImage andBlock:^(NSString *imageKey) {
                              NSLog(@"imageKey----%@",imageKey);
                              strongSelf.imageKey = imageKey;
                         
              
                          }];
          }
       
      }];
      imagePickerVc.modalPresentationStyle = 0;
      [self presentViewController:imagePickerVc animated:YES completion:nil];
    
    
}
#pragma mark -- 上传封面到七牛
-(void)upLoadImageToQINiu:(UIImage *)coverImg andBlock:(void (^)(NSString  *))imageBackBlock{
    
    if (self.kUploadIconImageToken) {
        
        NSData *data =UIImageJPEGRepresentation(coverImg, 0.8);
        
        QNUploadManager *upManager = [[QNUploadManager alloc] init];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *key = [NSString stringWithFormat:@"iOS%@.jpg", [formatter stringFromDate:[NSDate date]]];
        [upManager putData:data key:key token:self.kUploadIconImageToken
                  complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      if (!kDictIsEmpty(resp)) {
                          !imageBackBlock ? : imageBackBlock([resp jsonString:@"key"]);
                      }
                  } option:nil];
    }else{
        [self getAvatarQiniuToken];
    }
}

//获取七牛头像token
-(void)getAvatarQiniuToken{
    WEAKSELF
    [[SmileHttpTool sharedInstance] getTokenFromQiNiu:@"" resultBlock:^(BOOL isSuccess, NSString *token) {
        STRONGSELFFor(weakSelf)
        if (isSuccess) {
            strongSelf.kUploadIconImageToken = token;
        }
    }];
}
-(void)updateNickNameAndHeadImage{
    
    [self.view endEditing:YES];
    
    if ([self JudgeTheillegalCharacter:self.infoView.nameTF.text]==YES) {
        [JMNotifyView showNotify:@"昵称不能包含特殊字符" isSuccessful:NO];
        return;
    }
    
    [self showLoadingAnimation];

    NSString  * loginurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"user_updateNickNameAndHeadImage"];
       NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
       [diccc setValue:self.imageKey forKey:@"headImage"];
      [diccc setValue:self.infoView.nameTF.text forKey:@"nikeName"];
       //[diccc setValue:@"iOS" forKey:@"macAddress"];
       WEAKSELF
       [[SmileHttpTool sharedInstance] POST :loginurl parameters:diccc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
         STRONGSELFFor(weakSelf)

           if (statusCode==0) {
              [JMNotifyView showNotify:@"保存成功" isSuccessful:YES];
              [[NSNotificationCenter defaultCenter] postNotificationName:LoginSusessNotificationse object:nil];
              [strongSelf dismissViewControllerAnimated:YES completion:nil];
           }else{
                [JMNotifyView showNotify:message isSuccessful:NO];
           }

            [strongSelf stopLoadingAnimation];
       } failure:^(id responseObject, NSError *error) {
           NSLog(@"error----%@",error);
           [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
           [self stopLoadingAnimation];
       }];
    
    //[self reBtnClik];

}
-(void)reBtnClik{
    
     [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker{
    
    
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
